package models;

import play.*;
import play.db.jpa.*;

import javax.persistence.*;

import java.util.*;

/**
 * PlanRating.java Purpose: Model
 * 
 * @version 1.0 4/25/2011
 * @author Ahmed Mahmoud
 */

@Entity
public class PlanRating extends Model {

	@ManyToOne(cascade=CascadeType.PERSIST)
	public Plan plan;
	@ManyToOne(cascade=CascadeType.PERSIST)
	public User user;

	public int rating;

	/**
	 * 
	 * @param plan
	 *            the plan which was rated.
	 * @param user
	 *            the user who rated the plan.
	 * @param rating
	 *            the rating which was chosen by the user for this plan
	 */
	public PlanRating(Plan plan, User user, int rating) {
		this.plan = plan;
		this.user = user;
		this.plan.usersRatings.add(this);
		this.user.plansRatings.add(this);
		this.plan.save();
		this.user.save();
		this.rating = rating;
	}

	/**
	 * it takes rating as parameter and then update the rating for this record.
	 * 
	 * @param rating
	 *            the rating which the user has chosen for certain plan.
	 * @param newPlanRating
	 *            the whole rating for the plan.
	 * @return PlanRating, the PlanRating object that was modified.
	 */
	public PlanRating updateRating(int rating, double newPlanRating) {
		plan.updateRating(newPlanRating); // the whole value
		this.rating = rating;
		this.save();
		return this;
	}
	
	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * 
	 */
	public boolean cascadeDelete(){
		plan.usersRatings.remove(this);
		plan.save();
		user.plansRatings.remove(this);
		user.save();
		
		this.delete();
		return true;
	}

}
